package com.emapp.lccode.activity

import android.annotation.SuppressLint
import android.app.DatePickerDialog.OnDateSetListener
import android.content.Intent
import android.os.Bundle
import android.view.inputmethod.EditorInfo
import android.widget.DatePicker
import androidx.lifecycle.Observer
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.lifecycle.lifecycleOwner
import com.afollestad.materialdialogs.list.listItems
import com.emapp.lccode.R
import com.emapp.lccode.adapter.ProjectDeviceAdapter
import com.emapp.lccode.base.BaseActivity1
import com.emapp.lccode.base.BaseConfig
import com.emapp.lccode.base.EventBusConfig
import com.emapp.lccode.base.EventBusModel
import com.emapp.lccode.bean.DeviceKt
import com.emapp.lccode.bean.SelectType
import com.emapp.lccode.databinding.ActivityProjectDeviceListBinding
import com.emapp.lccode.mode.ProjectDeviceViewModel
import com.emapp.lccode.utils.MmkvUtil
import com.emapp.lccode.utils.setOnclickNoRepeat
import com.emapp.lccode.utils.statesListall
import com.emapp.lccode.utils.toJsonStr
import com.emapp.lccode.utils.vertical
import com.emapp.lccode.view.ProjectDeviceTypeDialog
import com.gyf.immersionbar.ktx.immersionBar
import com.hjq.toast.Toaster
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import me.hgj.jetpackmvvm.ext.parseState
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**项目
 */
class ProjectDeviceListActivity :
    BaseActivity1<ProjectDeviceViewModel, ActivityProjectDeviceListBinding>(),
    OnDateSetListener, ProjectDeviceTypeDialog.SelectTypeListener {
    var datas: ArrayList<DeviceKt> = arrayListOf()
    private val projectAdapter: ProjectDeviceAdapter by lazy { ProjectDeviceAdapter() }
    private var keywords = ""
    private var project_id = ""
    private var device_type = ""
    private var project_name = ""
    private var build_status = ""
    var page = 1
    override fun initView(savedInstanceState: Bundle?) {
        immersionBar {
            titleBar(mViewBind.lvTitle.ivBar)
            statusBarDarkFont(true)
            fullScreen(true)
            statusBarColor(R.color.transparent)
            navigationBarColor(R.color.white)
        }
        project_id = intent.getStringExtra("project_id").toString()
        project_name = intent.getStringExtra("project_name").toString()
        mViewBind.lvTitle.tvTitle.text = project_name
        mViewBind.lvTitle.tvRight.text = ""
        EventBus.getDefault().register(this)
        mViewBind.rvList.run {
            vertical()
            adapter = projectAdapter
        }
        projectAdapter.run {
            setOnItemClickListener { adapter, _, position ->
                val item = adapter.items[position]
                val intent =
                    Intent(this@ProjectDeviceListActivity, ProjectAddKtActivity::class.java)
                intent.putExtra("flag", "edit")
               // intent.putExtra("infor", item)
               // intent.putExtra("json_text", item.json_text)
                intent.putExtra("project_id", project_id)
                intent.putExtra("project_name", project_name)
                MmkvUtil.putString("infor",item.toJsonStr())
                MmkvUtil.putString("json_text",item.json_text)
//                EventBus.getDefault().postSticky(EventBusModel(EventBusConfig.INTENT_INFOR,item))
//                EventBus.getDefault().postSticky(EventBusModel(EventBusConfig.INTENT_INFOR,item.json_text))
                startActivity(intent)
            }
            isEmptyViewEnable = true
            emptyView = layoutInflater.inflate(R.layout.listitem_empty, mViewBind.rvList, false)
            projectAdapter.submitList(datas)
        }
        mViewBind.refreshLayout.run {
            setRefreshHeader(ClassicsHeader(this@ProjectDeviceListActivity))
            setRefreshFooter(ClassicsFooter(this@ProjectDeviceListActivity))
            setOnRefreshListener {
                page = 1
                getList()
            }
            setOnLoadMoreListener {
                page++
                getList()
            }
        }
        showLoading()
        getList()
        mViewBind.tvSearch.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                keywords = v.text.toString().trim()
                showLoading()
                page = 1
                getList()
                true
            } else {
                false
            }
        }
    }

    private fun getList() {
        mViewModel.getProjectDevicePageList(project_id, device_type, build_status, keywords, page)
    }

    override fun createObserver() {
        mViewModel.run {
            myProjectDevicePageList.observe(
                this@ProjectDeviceListActivity,
                Observer { resultState ->
                    parseState(resultState, {
                        if (page == 1) {
                            datas.clear()
                            if (it.data != null) {
                                datas.addAll(it.data)
                                if (it.data.size < BaseConfig.page_count) {
                                    mViewBind.refreshLayout.finishRefreshWithNoMoreData()
                                } else {
                                    mViewBind.refreshLayout.finishRefresh()
                                }
                            } else {
                                mViewBind.refreshLayout.finishRefreshWithNoMoreData()
                            }
                        } else {
                            if (it.data != null) {
                                datas.addAll(it.data)
                                if (it.data.size < BaseConfig.page_count) {
                                    mViewBind.refreshLayout.finishLoadMoreWithNoMoreData()
                                } else {
                                    mViewBind.refreshLayout.finishLoadMore()
                                }
                            } else {
                                mViewBind.refreshLayout.finishLoadMoreWithNoMoreData()
                            }
                        }
                        projectAdapter.notifyDataSetChanged()
                    }, {
                        Toaster.show(it.errorMsg)
                        mViewBind.refreshLayout.finishRefreshWithNoMoreData()
                    })
                })
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    @SuppressLint("CheckResult")
    override fun onBindViewClick() {
        setOnclickNoRepeat(
            mViewBind.lvTitle.ivLeft,
            mViewBind.btSearch,
            mViewBind.tvType,
            mViewBind.tvState,
            mViewBind.lvTitle.tvRight
        ) {
            when (it.id) {
                R.id.iv_left -> {
                    finish()
                }

                R.id.tv_right -> {
                }

                R.id.tv_type -> {
                    mViewModel.projectDevicetypeDialog.listener = this
                    mViewModel.projectDevicetypeDialog.project_id = project_id
                    mViewModel.projectDevicetypeDialog.selectType = mViewModel.selectType
                    mViewModel.projectDevicetypeDialog.show(this)
                }

                R.id.tv_state -> {
                    MaterialDialog(this).show {
                        cancelable(true)
                        lifecycleOwner(this@ProjectDeviceListActivity)
                        listItems(null, statesListall) { v, index, text ->
                            mViewBind.tvState.text = text
                            build_status = when (text) {
                                "未开工" -> "1"
                                "建设中" -> "2"
                                "已竣工" -> "3"
                                "全部" -> ""
                                else -> {
                                    ""
                                }
                            }
                            getList()
                        }
                    }
                }

                R.id.bt_search -> {
                    keywords = mViewBind.tvSearch.text.toString().trim()
                    showLoading()
                    page = 1
                    getList()
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(event: EventBusModel) {
        when (event.type) {
            EventBusConfig.REFRESH_PROJECT_DEVICE -> {
                page = 1
                getList()
            }

            else -> {}
        }
    }


    override fun onDateSet(view: DatePicker?, year: Int, month: Int, dayOfMonth: Int) {
    }

    override fun onSelectTypeComplete(type: SelectType) {
        mViewModel.selectType = type
        device_type = type.device_type
        var t = type.name0
        if (!type.device_type_name.isNullOrBlank())
            t = "$t,${type.device_type_name}"
        mViewBind.tvType.text = t
        page = 1
        getList()
    }

}
